package com.skh.string;

/**
 * @Author skh
 * @Date 2020/3/29 14:31
 * @Desc  单词距离
 */
public class FindClosest {

    /**
     * 有个内含单词的超大文本文件，给定任意两个单词，找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次，而每次寻找的单词不同，你能对此优化吗?
     *
     * 示例：
     *
     * 输入：words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student"
     * 输出：1
     *
     */

    //扫一遍集合，记录word1和word2上一次出现位置，扫到word1或者word2时更新答案。
    public int findClosest(String[] words, String word1, String word2) {
        int distance = Integer.MAX_VALUE;
        int index1 = -1;
        int index2 = -1;

        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            if (word.equals(word1)) {
                index1 = i;
                if (index2 != -1) {
                    distance = Math.min(distance, index1 - index2);
                }
            } else if (word.equals(word2)) {
                index2 = i;
                if (index1 != -1) {
                    distance = Math.min(distance, index2 - index1);
                }
            }
        }

        return distance;
    }
}
